package com.yang.controller;

import com.yang.exception.BusinessException;
import com.yang.pojo.SysUser;
import com.yang.service.SysUserService;
import com.yang.utils.Constants;
import com.yang.utils.CommonUtil;
import com.yang.utils.JsonResult;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/email")
public class SendEmailController {
    @Resource
    RedisTemplate<String, Integer> redisTemplate;
    @Resource
    SysUserService sysUserService;
    @Resource
    JavaMailSender mailSender;

    @GetMapping("/send")
    public Map<String,Object> send(@RequestParam("username") String username,@RequestParam("email") String email){
        JsonResult jsonResult = new JsonResult();
        try {
            SysUser byUsername = sysUserService.findByUsername(username);
            if (byUsername == null){
                throw new BusinessException("您还未注册，请先注册");
            }
            if (!byUsername.getEmail().equals(email)){
                throw new BusinessException("用户名或邮箱错误");
            }
            /* 获取验证码*/
            Integer code = CommonUtil.getCode();
            /* 通过邮件发送验证码*/
            SimpleMailMessage message = new SimpleMailMessage();
            // 发件人
            message.setFrom(Constants.EMAIL_FROM);
            // 收件人
            message.setTo(email);
            // 邮件标题
            message.setSubject(Constants.EMAIL_SUBJECT);
            // 邮件内容
            message.setText("您正在修改密码，如果非本人操作请忽略。您的验证码为："+code+"，有效时间为15分钟。");
            mailSender.send(message);
            /* 将验证码存储到redis数据库，设置有效时间为15分钟*/
            redisTemplate.opsForValue().set(email,code,15, TimeUnit.MINUTES);

            jsonResult.setCode("200");
            jsonResult.setMsg("发送成功");
        }catch (Exception e){
            e.printStackTrace();
            throw new BusinessException("发送失败");
        }
        return jsonResult.getValues();
    }
}
